<template>
   <table>
      <thead>
         <tr>
            <th v-for="title in titles" :key="title">{{ title }}</th>
         </tr>
      </thead>
      <tbody>
         <tr
            v-for="(item, index) in data"
            :key="index"
            draggable="true"
            @dragstart="handleDragStart(item)"
            @dragenter="handleDragEnter($event, item)"
            @dragend="handleDragEnd(item)"
         >
            <td>{{ item.content }}</td>
         </tr>
      </tbody>
   </table>
</template>

<script lang="ts" setup>
import { ref } from "vue"
   interface Props {
      titles: Array<string>;
      data: Array<any>;
      textfield: string;
   }

const emit = defineEmits(["change-item"])

const props = withDefaults(defineProps<Props>(), {
   textfield: "name"
})

const dragging = ref<any>(null)

const handleDragStart = (item: any) => {
   dragging.value = item // 开始拖动时，暂时保存当前拖动的数据。
}
const handleDragEnd = (item: any) => {
   dragging.value = null
}

const handleDragEnter = (e: Event, item: any) => {
   if (item == dragging.value) return
   const newItems = [...props.data] // 拷贝一份数据进行交换操作。
   const idx = newItems.indexOf(dragging.value) // 获取数组下标
   const dst = newItems.indexOf(item)
   newItems.splice(dst, 0, ...newItems.splice(idx, 1)) // 交换位置
   emit("change-item", newItems)
}
</script>

<style scoped lang="less"></style>
